<template>
  <div class="index-container">
    <h1 class="welcome-title">欢迎来到聊天室</h1>
    <div class="feature-list">
      <el-card class="feature-card">
        <h3>开始聊天</h3>
        <p>加入现有房间或创建新房间</p>
        <div class="button-group">
          <el-button type="primary" @click="enterChat">进入聊天室</el-button>
          <el-button @click="showOnlineUsers = true">看看谁在线</el-button>
        </div>
      </el-card>
    </div>

    <!-- 在线用户抽屉 -->
    <el-drawer
      title="在线用户"
      :visible.sync="showOnlineUsers"
      direction="rtl"
      size="300px">
      <div class="user-list">
        <div 
          v-for="user in onlineUsers" 
          class="user-item"
          @click="startPrivateChat(user)"
        >
          <div class="avatar">{{ user?.charAt(0).toUpperCase() }}</div>
          <span class="username">{{ user }}</span>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showOnlineUsers: false,
      onlineUsers: [] // 在线用户列表
    }
  },
  methods: {
    startPrivateChat(user) {
      this.$router.push({ path: '/chat/private/' + user })
      this.showOnlineUsers = false // 关闭抽屉
    },
    enterChat() {
      this.$router.push('/chat')
    },
    async loadOnlineUsers() {
      try {
        await this.$axios.post('/user/getOnlineUserList',{
          username:JSON.parse(localStorage.getItem('user')).username
        }).then(response => {
          if (response.data.code === 200) {
            localStorage.setItem('onlineUserList', JSON.stringify(response.data.data));
            this.onlineUsers = response.data.data;
          }
        })
      } catch (error) {
        console.error('获取在线用户失败:', error)
      }
    },
    async loadUnReadMessageCount() {
            this.$axios.post('/message/getUnReadMessageListByUsername',{
                username: JSON.parse(localStorage.getItem('user')).username
            }).then(response => {
                if (response.data.code === 200) {
                    localStorage.setItem('messageList', JSON.stringify(response.data.data.messageList));
                    localStorage.setItem('unreadList', JSON.stringify(response.data.data.unreadList));
                    localStorage.setItem('unreadCount', response.data.data.data);
                }
            }) 
        }
  },
  watch: {
    showOnlineUsers(val) {
      if (val) {
        this.loadOnlineUsers()
      }
    }
  },
  created() {
    this.loadUnReadMessageCount()
  }
}
</script>

<style scoped>
@import url('../assets/css/views/index.css');
</style>